﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Xml;

namespace UFSControl
{
    public partial class EPGDetail : Form
    {
        private string vURL;
        private string vAddTimerURL;
        private string vDeleteTimerURL;
        private string vDetailURL;
        private Boolean vDayLightSaving;

        public EPGDetail(string aBaseUrl, string channelNo, string tvtId, string channelName)
        {
            InitializeComponent();
            //Variablen anlegen
            vURL = aBaseUrl + "/xmlfeeds/scheduleEpgTable?start-index=" + channelNo;
            //vAddTimerURL = aBaseUrl + "/cmds/setTimer?channel-no=" + channelNo + "&tvtv-Id=" + tvtId;
            vAddTimerURL = aBaseUrl + "/SetTimer/" + String.Format("{0:00000}T{1:00000}", (Convert.ToInt32(channelNo)).ToString("D5"), (Convert.ToInt32(tvtId)).ToString("D5"));
            vDeleteTimerURL = aBaseUrl + "/DeleteTimer/";
            vDetailURL = aBaseUrl + "/xmlfeeds/detailedInfo?start-index=" + channelNo; 
            //Name setzen
            this.Text = "EPG - " + channelName;
            vDayLightSaving = TimeZoneInfo.Local.IsDaylightSavingTime(DateTime.Now);
            //Columns anlegen
            listView1.Columns.Add("1", "Icon", 40);
            listView1.Columns.Add("2", "Programm", 260);
            listView1.Columns.Add("3", "Zeit", 100);
            listView1.Columns.Add("4", "TimerNr.", 0);
            //listView1.Columns.Add("4", "tvtvId", 60);
            //listView1.Columns.Add("5", "progId", 60);

            createDetailEPG();
        }

        //an eine Webadresse einen REquest schicken und das Ergebnis als String zurückliefern
        private string SendWebRequest(Uri aURL)
        {
            string lresponseFromServer = "";

            WebRequest lRequest = WebRequest.Create(aURL);
            ((HttpWebRequest)lRequest).UserAgent = "Eigenbau";
            lRequest.Method = "GET";
            lRequest.ContentType = "text/html";
            //Stream ldataStream = lrequest.GetRequestStream();
            // Set the 'Timeout' property in Milliseconds.
            lRequest.Timeout = 10000;
            try
            {
                // Get the response.
                WebResponse lResponse = lRequest.GetResponse();

                // Get the stream containing content returned by the server.
                Stream ldataStream = lResponse.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader lreader = new StreamReader(ldataStream);
                // Read the content.
                lresponseFromServer = lreader.ReadToEnd();

                // Clean up the streams.
                lreader.Close();
                ldataStream.Close();
                lResponse.Close();
                return lresponseFromServer;
            }
            catch
            {
                //Timeout abfangen
                MessageBox.Show("Request timed out");
                return ""; //Programm verlassen

            }
        }

        private string PrintDayOfWeek(DayOfWeek day)
        {
            switch (day)
            {
                case DayOfWeek.Monday:
                    return "Mo";
                case DayOfWeek.Tuesday:
                    return "Di";
                case DayOfWeek.Wednesday:
                    return "Mi";
                case DayOfWeek.Thursday:
                    return "Do";
                case DayOfWeek.Friday:
                    return "Fr";
                case DayOfWeek.Saturday:
                    return "Sa";
                case DayOfWeek.Sunday:
                    return "So";
            }
            return "  ";

        }

        private void createDetailEPG()
        {
            Uri lUri = new Uri(vURL + "&max-results=60");
            string lResponse = SendWebRequest(lUri);
            if (lResponse == "") { return; }
            //XML Elemente durchgehen
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(lResponse);
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("./event");
            try
            {
                string title = "";
                string catIcon = "";
                string zeit = "";
                string startTime = "";
                string progId = "";
                float zeitPzt = 0;
                string timerNo = "";
                DateTime UnixEpoch;
                foreach (XmlNode i in nodes)
                {
                    title = i["title"].InnerText;
                    if (i["progress"] != null) { zeitPzt = (float)Convert.ToDouble(i["progress"].InnerText); } else { zeitPzt = 0; }
                    if (i["progId"] != null) { progId = i["progId"].InnerText; } else { progId = ""; }
                    if (i["catIcon"] != null) { 
                        catIcon = i["catIcon"].InnerText;
                        catIcon = catIcon.Replace("/icon/", "");
                    } else { 
                        catIcon = ""; 
                    }
                    if (i["startTime"] != null)
                    {
                        startTime = i["startTime"].InnerText;
                        UnixEpoch = new DateTime(Convert.ToInt64(i["startTime"].InnerText) * 10000000); //Ticks
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }// Time Offset
                        zeit = String.Format("{0} {1:00}:{2:00}", PrintDayOfWeek(UnixEpoch.DayOfWeek), UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    else
                    {
                        zeit = "";
                        startTime = "";
                    }
                    if (i["endTime"] != null)
                    {
                        UnixEpoch = new DateTime(Convert.ToInt64(i["endTime"].InnerText) * 10000000 + 36000000000); //Ticks 
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }// Time Offset
                        zeit += " - " + String.Format("{0:00}:{1:00}", UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    if (i["timerNo"] != null) { timerNo = i["timerNo"].InnerText; } else { timerNo = ""; }
                    ListViewItem listItem = listView1.Items.Add(new ListViewItem(new string[] { "", title, zeit, progId, startTime, timerNo }));
                    //Kategorie Icon auswählen
                    if (catIcon != ""){ (listItem).ImageIndex = Convert.ToInt16(catIcon); } else { (listItem).ImageIndex = 0; }

                }
            }
            catch
            {
            }
        }

        private void OnAddTimerClick(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            //Timer hinzufügen
            //string channelNr = listView1.SelectedItems[0].Text;
            //Uri lUri = new Uri(vAddTimerURL + "&start-time=" + listView1.SelectedItems[0].SubItems[3].Text);
            //beim Zeitwert muss 3600 addiert werden
            Int64 time = Convert.ToInt64(listView1.SelectedItems[0].SubItems[4].Text);
            if (vDayLightSaving) { time += 7200; } else { time += 3600; }// Time Offset
            Uri lUri = new Uri(vAddTimerURL + "S" + time.ToString());
            string lresponseFromServer = SendWebRequest(lUri); 
            //den Response noch bearbeiten: wenn Timer gesetzt kommt, dann auch den Eintrag auf Rec umstellen
            if (lresponseFromServer.IndexOf("Timer gesetzt!") > 0)
            {
                //Timer gesetzt
                MessageBox.Show("Timer wurde gesetzt");
                listView1.SelectedItems[0].ImageIndex = 4; //Rec Icon anzeigen
            }
            else
            {
                //Fehler
                MessageBox.Show("Timer konnte nicht gesetzt werden");
            }
        }

        private void contextMenu_Opening(object sender, CancelEventArgs e)
        {
            if (listView1.SelectedItems[0].SubItems[5].Text != "")
            {
                //Aufname Icon gefunden, nur löschen aktiv schalten
                timerHinzufuegen.Visible = false;
                timerLoeschen.Visible = true;
            }
            else
            {
                //kein Aufname Icon gefunden, daher nur Aufnahme aktiv
                timerHinzufuegen.Visible = true;
                timerLoeschen.Visible = false;
            }

        }

        private void timerLoeschen_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            //Timer löschen
            Uri lUri = new Uri(vDeleteTimerURL + listView1.SelectedItems[0].SubItems[4].Text);
            string lresponseFromServer = SendWebRequest(lUri);
            //den Response noch bearbeiten: wenn Timer gesetzt kommt, dann auch den Eintrag auf Rec umstellen
            if (lresponseFromServer.IndexOf("Timer gel&ouml;scht!") > 0)
            {
                //Timer gesetzt
                MessageBox.Show("Timer wurde gelöscht");
                listView1.SelectedItems[0].ImageIndex = 0; //Icon löschen
            }
            else
            {
                //Fehler
                MessageBox.Show("Timer konnte nicht gelöscht werden");
            }
        }

        //EPG Text laden und anzeigen
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count <= 0)
            {
                return;
            }
            //zu Sender detail Info anzeigen
            Uri lUri = new Uri(vDetailURL + "&start-time=" + listView1.SelectedItems[0].SubItems[4].Text);

            string lresponseFromServer = SendWebRequest(lUri); 
            //XML Elemente durchgehen
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(lresponseFromServer);
            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("./event");
            try
            {
                string longInfo;
                string zeit = "";
                DateTime UnixEpoch;
                richTextBox.Text = ""; //Text leer setzen, vielleicht ist ja kein Dokument geschickt worden
                foreach (XmlNode i in nodes)
                {
                    if (i["longInfo"] != null)
                    {
                        longInfo = i["longInfo"].InnerText;
                        longInfo = longInfo.Replace("<br>", "\n");
                    }
                    else
                    {
                        longInfo = "";
                    }
                    if (i["startTime"] != null)
                    {
                        UnixEpoch = new DateTime(Convert.ToInt64(i["startTime"].InnerText) * 10000000); //Ticks
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }// Time Offset
                        zeit = String.Format("{0:00}:{1:00}", UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    else { zeit = ""; }
                    if (i["endTime"] != null)
                    {
                        UnixEpoch = new DateTime(Convert.ToInt64(i["endTime"].InnerText) * 10000000); //Ticks +1h offset
                        if (vDayLightSaving) { UnixEpoch = UnixEpoch.AddHours(2); } else { UnixEpoch = UnixEpoch.AddHours(1); }// Time Offset
                        zeit += " - " + String.Format("{0:00}:{1:00}", UnixEpoch.Hour, UnixEpoch.Minute);
                    }
                    richTextBox.Text = zeit + "\n" + longInfo;
                }
            }
            catch
            {
            }
        }
    }
}
